package com.aynu.gulimall.ware.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mj
 * @version 1.0
 * @date 2021/4/8 23:57
 */
@Configuration
public class MyRabbitConfig {

    /**
     * 使用JSOn序列化机制，进行消息转换
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 创建库存交换机
     * @return
     */
    @Bean
    public Exchange stockEventExchange(){
        return new TopicExchange("stock-event-exchange",true,false);
    }

    /**
     * 普通队列
     * @return
     */
    @Bean
    public Queue stockReleaseStockQueue(){
        return new Queue("stock.release.stock.queue",true,false,false);
    }

    /**
     * 延迟队列，死信队列
     * @return
     */
    @Bean
    public Queue stockDelayStockQueue(){
        //创建死信队列特殊属性
        Map<String,Object> arguments = new HashMap<>();
        //死信路由
        arguments.put("x-dead-letter-exchange","stock-event-exchange");
        //死信路由键
        arguments.put("x-dead-letter-routing-key","stock.release");
        //消息过期时间
        arguments.put("x-message-ttl",120000);//两分钟
        return new Queue("stock.delay.queue",true,false,false,arguments);
    }

    /**
     * 交换机与普通队列绑定
     * @return
     */
    @Bean
    public Binding stockReleaseBinding(){
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",null);
    }

    /**
     * 交换机与普通队列绑定
     * @return
     */
    @Bean
    public Binding stockLockedBinding(){
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",null);
    }
}
